package com.getpebble.android.common.core.trace;

import android.content.Context;
import android.os.Build;
import android.os.Build.VERSION;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import java.util.Locale;
import java.util.Map;

class AndroidDevice {
    private static String sUuidAsString = null;

    public static void addStaticProperties(Context context) {
        Map<String, Object> event = AnalyticsLogger.getStaticGlobalProperties();
        if (!event.containsKey("platform")) {
            event.put("platform", "android");
        }
        AnalyticsLogger.getOrCreateChildMap(event, "app").put("locale", context.getResources().getConfiguration().locale.toString());
        Map<String, Object> phone = AnalyticsLogger.getOrCreateChildMap(event, "device_phone");
        phone.put("locale", Locale.getDefault().toString());
        phone.put("system_name", "Android OS");
        phone.put("model", getModel());
        phone.put("system_version", VERSION.RELEASE);
        Map<String, Object> identity = AnalyticsLogger.getOrCreateChildMap(event, "identity");
        String deviceUuid = getDeviceUuid(context).toUpperCase();
        identity.put("device", deviceUuid);
        event.put("session", deviceUuid);
        AnalyticsLogger.setStaticGlobalProperties();
    }

    public static String getDeviceUuid(Context anyContext) {
        if (sUuidAsString == null) {
            loadDeviceUuid(anyContext);
        }
        return sUuidAsString;
    }

    public static String getModel() {
        String manufacturer = Build.MANUFACTURER;
        String model = Build.MODEL;
        if (model.startsWith(manufacturer)) {
            return capitalize(model);
        }
        return capitalize(manufacturer) + " " + model;
    }

    private static String capitalize(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        char first = s.charAt(0);
        return !Character.isUpperCase(first) ? Character.toUpperCase(first) + s.substring(1) : s;
    }

    private static synchronized void loadDeviceUuid(Context anyContext) {
        synchronized (AndroidDevice.class) {
            if (sUuidAsString == null) {
                String androidId = Secure.getString(anyContext.getContentResolver(), "android_id");
                if ("9774d56d682e549c".equals(androidId)) {
                    String deviceId = ((TelephonyManager) anyContext.getSystemService("phone")).getDeviceId();
                    if (deviceId == null) {
                        deviceId = "unknown";
                    }
                    sUuidAsString = deviceId;
                } else {
                    sUuidAsString = androidId;
                }
            }
        }
    }
}
